package com.easilyj.realm;

import com.easilyj.bean.User;
import com.easilyj.constant.RoleConstant;
import com.easilyj.service.UserService;
import com.easilyj.shiro.UserToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public class UserShiroRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(UserShiroRealm.class);

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("【用户授权】doGetAuthorizationInfo...");
        User user = (User) principalCollection.getPrimaryPrincipal();
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            if (user.getUserLevelId().equals(RoleConstant.LEVEL_USER)) {
                info.addRole(RoleConstant.ROLE_USER);
            }
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        logger.info("【用户认证】doGetAuthenticationInfo...");
        UserToken userToken = (UserToken) token;
        User user = userService.findByUserEmail(userToken.getUsername());
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        return new SimpleAuthenticationInfo(user, user.getUserPassword(), ByteSource.Util.bytes(user.getUserEmail()), getName());
    }
}
